/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.servicecomb.filter;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.StringUtil;
import com.je.servicecomb.MicroCommonConstants;
import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
import org.apache.servicecomb.core.Invocation;
import org.apache.servicecomb.foundation.vertx.http.HttpServletRequestEx;
import org.apache.servicecomb.swagger.invocation.Response;

import java.net.URLDecoder;
import java.util.List;

public class DynabeanArgumentServerFilter extends AbstractHttpServerFilter implements HttpServerFilter {

    private BeanService beanService;

    public BeanService getBeanService() {
        if(beanService == null){
            synchronized (this){
                if(beanService == null){
                    beanService = SpringContextHolder.getBean(BeanService.class);
                    return beanService;
                }
            }
        }
        return beanService;
    }

    @Override
    public int getOrder() {
        return 101;
    }

    private void setContextParamsToAttribute(Invocation invocation,HttpServletRequestEx request){
        String contextJeParamKeys = invocation.getContext().get(MicroCommonConstants.CONTEXT_JE_PARAMS_KEY);
        if(!Strings.isNullOrEmpty(contextJeParamKeys)){
            List<String> keys = Splitter.on(",").splitToList(contextJeParamKeys);
            String value;
            for (String eachKey : keys) {
                value = invocation.getContext().get(eachKey);
                if(!Strings.isNullOrEmpty(value)){
                    request.setAttribute(eachKey, URLDecoder.decode(value));
                }else {
                    request.setAttribute(eachKey, value);
                }
                //清理上下文
                invocation.getContext().remove(eachKey);
            }
        }
    }

    @Override
    public Response afterReceiveRequest(Invocation invocation, HttpServletRequestEx request) {
        //setContextParamsToAttribute(invocation,request);

        //得到表的Code
        String tableCode = getStringParameter(request,"tableCode");
        String viewTableCode = getStringParameter(request,"viewTableCode");

        //赋值查询条件
        String whereSql = getStringParameter(request,"whereSql");
        //TODO 先注释掉，神通数据库有问题，再放开  huxuanhua
       /* if(!StringUtil.isEmpty(whereSql)&&PCDaoTemplateImpl.DBNAME.equals(ConstantVars.STR_SHENTONG)){
            whereSql = whereSql.replaceAll("!=''"," is not null ").replaceAll("=''"," is null ");
        }*/
        if(StringUtil.isEmpty(whereSql)){
            whereSql="";
        }

        //赋值排序条件
        String orderSql = getStringParameter(request,"orderSql");
        if(StringUtil.isEmpty(orderSql)){
            orderSql="";
        }

        DynaBean dynaBean = null;
        if(StringUtil.isNotEmpty(tableCode)) {
            //封装DynaBean
            dynaBean = new DynaBean(tableCode,false);
            if(request.getParameterMap().containsKey("pkCode")){
                dynaBean.setStr(BeanService.KEY_PK_CODE,request.getParameter("pkCode"));
            }
            //根据表Code得到表资源对象
            DynaBean resourceTable =null;
            if(StringUtil.isNotEmpty(viewTableCode)){
                resourceTable = getBeanService().getResourceTable(viewTableCode);
            }else{
                resourceTable = getBeanService().getResourceTable(tableCode);
            }
            //得到所有的key和columns
            List<DynaBean> allColumns = resourceTable.getDynaBeanList(BeanService.KEY_TABLE_COLUMNS);
            List<DynaBean> allKeys = resourceTable.getDynaBeanList(BeanService.KEY_TABLE_KEYS);
            // 给所有的列赋值
            for (DynaBean column : allColumns) {
                // 根据列名得到值
                String columnName = column.getStr("TABLECOLUMN_CODE");
                String value = getStringParameter(request,columnName);
                boolean isContainKey = containParameter(request,columnName);
                if(isContainKey && value==null){
                    dynaBean.set(columnName,null);
                    continue;
                }else if(value == null){
                    continue;
                }

                if ("VARCHAR".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR30".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR50".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR100".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR255".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR767".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR1000".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR2000".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "VARCHAR4000".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "CLOB".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "BIGCLOB".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "ID".equals(column.getStr("TABLECOLUMN_TYPE"))
                        || "CUSTOMID".equals(column.getStr("TABLECOLUMN_TYPE"))) {
                    dynaBean.setStr(column.getStr("TABLECOLUMN_CODE"), value);
                }else if ("DOUBLE".equals(column.getStr("TABLECOLUMN_TYPE"))) {
                    //研发部:云凤程改 2012年12月7日
                    if(!"".equals(value)&&value!=null){
                        dynaBean.setDouble(columnName, Double.parseDouble(value));
                    }
                }else if ("FLOAT".equals(column.getStr("TABLECOLUMN_TYPE")) || "FLOAT2".equals(column.getStr("TABLECOLUMN_TYPE"))) {
                    //研发部:云凤程改 2012年12月7日
                    if(!"".equals(value)&&value!=null){
                        dynaBean.setDouble(columnName, Double.parseDouble((value)));
                    }else{
                        dynaBean.setInt(columnName, 0);
                    }
                }else if ("NUMBER".equals(column.getStr("TABLECOLUMN_TYPE"))) {
                    //研发部:云凤程改 2012年12月7日
                    if(!"".equals(value)&&value!=null){
                        if(value.indexOf(".")!=-1){//如果包含小数
                            value=value.substring(0,value.indexOf("."));
                        }
                        dynaBean.setInt(columnName, Integer.parseInt(value));
                    }else{
                        //张帅鹏 改动   解决空值传过来数值型不update操作
                        dynaBean.setInt(columnName, 0);
                    }
                }else if ("YESORNO".equals(column.getStr("TABLECOLUMN_TYPE"))) {
                    // 平台处理Boolean类型存放为字符串。 则直接将value传入即可  无须解析  张帅鹏 2013年6月30日 22:20:39
//				dynaBean.set(columnName, Boolean.parseBoolean(value));
                    dynaBean.set(columnName,value);
                }else if ("CUSTOM".equals(column.getStr("TABLECOLUMN_TYPE"))) {
                    dynaBean.set(columnName, value);
                }else if("DATE".equals(column.getStr("TABLECOLUMN_TYPE"))){
                    dynaBean.setStr(columnName, value);
                }else if("DATETIME".equals(column.getStr("TABLECOLUMN_TYPE"))){
                    dynaBean.setStr(columnName, value);
                }else if("FOREIGNKEY".equals(column.getStr("TABLECOLUMN_TYPE"))){
                    if(StringUtil.isNotEmpty(value)){
                        dynaBean.setStr(columnName, value);
                    }else{
                        dynaBean.setStr(columnName, null);
                    }
                }else if("CUSTOMFOREIGNKEY".equals(column.getStr("TABLECOLUMN_TYPE"))){
                    if(StringUtil.isNotEmpty(value)){
                        dynaBean.setStr(columnName, value);
                    }else{
                        dynaBean.setStr(columnName, null);
                    }
                }
            }

            // 赋值主键
            for (DynaBean key : allKeys) {
                if ("Primary".equals(key.getStr("TABLEKEY_TYPE"))) {
                    dynaBean.set(BeanService.KEY_PK_CODE, key.getStr("TABLEKEY_COLUMNCODE"));
                }
                if ("CUSTOMID".equals(key.getStr("TABLEKEY_TYPE"))) {
                    dynaBean.set(BeanService.KEY_PK_CODE, key.getStr("TABLEKEY_COLUMNCODE"));
                }
            }
            dynaBean.set(BeanService.KEY_WHERE, whereSql);
            dynaBean.set(BeanService.KEY_ORDER, orderSql);
        }else{
            dynaBean = new DynaBean();
        }
        //将dynaBean赋值给request
        request.setAttribute("dynaBean",dynaBean);
        return null;
    }
}
